package com.lxy.mychat1.ui.home;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.lxy.mychat1.Adapter.ChatltemAdapter;
import com.lxy.mychat1.Bean.ChatItem;
import com.lxy.mychat1.Bean.Msg;
import com.lxy.mychat1.Bean.User;
import com.lxy.mychat1.R;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {
    ListView chatitemlv;
    ChatltemAdapter adapter;
    List<ChatItem> chatItemList=new ArrayList<>();
    List<User> userList=new ArrayList<>();
    List<Msg> msgList=new ArrayList<>();
    int myid;
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_home, container, false);
        initData();
        initView(root);
        return root;

    }

    private void initData() {
        SharedPreferences sp=getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
        myid=sp.getInt("myid",-1);
        userList= LitePal.where("id != ?",myid+"").find(User.class);
        for (User u:userList){
            msgList=getChatContent(u);
            if (msgList.size()!=0){
                Msg msg=msgList.get(msgList.size()-1);
                ChatItem chatItem=new ChatItem(u.getUserimg(),u.getName(),msg.getContent(),msg.getTime());
                chatItemList.add(chatItem);
            }
        }

    }

    private List<Msg> getChatContent(User u) {
        List<Msg> msgs=new ArrayList<>();
        for (Msg m:LitePal.findAll(Msg.class)){
            boolean a = myid == m.getSendid()&&u.getId()==m.getReceiveid();
            boolean b = myid == m.getReceiveid()&&u.getId()==m.getSendid();
            if (a||b){
                msgs.add(m);
            }
        }
        return msgs;
    }

    private void initView(View root) {
        chatitemlv=root.findViewById(R.id.chatitemlv);
        adapter=new ChatltemAdapter(getContext(),R.layout.chat_item,chatItemList);
        chatitemlv.setAdapter(adapter);
    }
}